package top.lishuoboy.ssm;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import top.lishuoboy.dependency.base.db.MyDbUtil;
import top.lishuoboy.ssm.bean.People;
import top.lishuoboy.ssm.bean.User;
import top.lishuoboy.ssm.mapper.UserMapper;

import javax.sql.DataSource;
import java.util.Map;

@Slf4j
public class SsmTest {
    public static final ApplicationContext context = new ClassPathXmlApplicationContext("classpath:SpringContext.xml");

    @Test
    public void testSpring() {
        People people = context.getBean(People.class);
        log.warn("people=={}", people);         // people==People(name=张三)
    }

    @Test
    @SneakyThrows
    public void testJdbcTemplate() {
        JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

        Map<String, Object> user = jdbcTemplate.queryForMap("select * from INFORMATION_SCHEMA.users");
        log.warn("user=={}", user);   // user=={NAME=ROOT, ADMIN=true, REMARKS=, ID=2}
    }

    /** 参考 mybatis-spring 官网：http://mybatis.org/spring/zh/index.html */
    @Test
    public void testMybatis() {
        resetDbData();
        SqlSessionFactory sqlSessionFactory = context.getBean(SqlSessionFactory.class);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectById(1);
        log.warn("user=={}", user);     // user==User(id=1, name=张三, psw=111)
    }

    /** 重置数据库 */
    @Test
    public void resetDbData() {
        MyDbUtil.resetData(context.getBean(DataSource.class), "db_sql/lishuoboy-ssm.sql");
    }
}